# -*- coding: utf-8 -*-
class SaleOrder < ActiveRecord::Base
  has_many :sale_order_details ,:dependent => :destroy      #级联删除子表
  has_many :purchase_order_details ,:dependent => :nullify  #级联删除子表,在这儿不可行。
  has_many :delivery_orders ,:dependent => :destroy         #级联删除子表
  has_many :receivables ,:dependent => :destroy             #级联删除子表
  has_many :sale_returneds

  
  has_one :purchase_order
  belongs_to :customer
  belongs_to :employee      #制单人员
  belongs_to :order_type
  belongs_to :department
  belongs_to :company
  belongs_to :sale_type
  belongs_to :sales_strategy  #销售策略
  
  belongs_to :sales, :class_name => 'Employee', :foreign_key => 'sales_id'      #此订单的销售员。
  belongs_to :auditor, :class_name => 'Employee', :foreign_key => 'auditor_id'
  belongs_to :delivery_employee, :class_name => 'Employee', :foreign_key => 'delivery_employee_id'
  belongs_to :sell_department, :class_name => 'Department', :foreign_key => 'sell_dept_id'

  #对比销售与出库的数量差别，这里只把已经撤消的排除在外，其它的状态比较申请状态的入库，我们都计算在内。所以在很多地方要把所有的申请都排除在外时，操作才可以顺畅。
  #这里是检查不出另一种情况的，就是出库比销售还多的情况，这里只能查询出入库比采购少的情况。
  scope :diff_sale_delivery, lambda { |saleOrderId| joins("so left join sale_order_details sod on so.id = sod.sale_order_id
                                  left join (select sum(dod.quantity) quantity,dod.product_id from delivery_orders do left join delivery_order_details dod on do.id = dod.delivery_order_id where do.sale_order_id = #{saleOrderId} AND do.auditing_status != '通过撤消' GROUP BY dod.product_id) outterdod on outterdod.product_id = sod.product_id
      ").where("so.id = ?",saleOrderId).select("sod.product_id,sum(sod.quantity) sod_quantity,ifnull(sum(outterdod.quantity),0) dod_quantity").group("sod.product_id").having("sod_quantity - dod_quantity != 0") }


          
  def self.findAllSaleOrders  conditionsStr,conditionsHash,paramsHash
    begin    
      find(
        :all,
        :conditions => [conditionsStr,conditionsHash],
        :include => [:employee,:department,:sell_department,:sale_type,:sales_strategy,:customer,:auditor,:delivery_employee,:sales,:sale_order_details],
        :offset => paramsHash[:offset],
        :limit => paramsHash[:limit],
        :order => 'sale_orders.updated_at DESC'
      )
    rescue Exception => e
      puts "Fuck From findAllSaleOrders"
      logger.info e
    end
  end

  def self.countAllSaleOrders  conditionsStr,conditionsHash
    begin
      count(
        :all,
        :include=>[:sale_order_details],
        :conditions => [conditionsStr,conditionsHash]
      )
    rescue Exception => e
      logger.info e
    end
  end
  
end
